package com.itheima.reggie.controller;


import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/addressBook")
public class AddressBookController {


    @Autowired(required = false)
    private AddressBookService addressBookService;
    /**
     * 新增收货地址
     * @param addressBook
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody AddressBook addressBook, HttpSession session){
        Long  id = (Long) session.getAttribute("user");
        System.out.println("登录用户的id是"+id);
       addressBook.setCreateUser(id);
       addressBook.setUpdateUser(id);
        addressBookService.addAddressBook(addressBook);
        return R.success("");
    }

    /**
     * 获取地址列表
     * @param session
     * @return
     */
    @GetMapping("list")
    public R<List<AddressBook>> list(HttpSession session){
        //获取登录用户id
        Long userId = (Long) session.getAttribute("user");
        List<AddressBook> addressBookList = addressBookService.findAllAddress(userId);
        return R.success(addressBookList);
    }

    /**
     * 数据回显：显示修改地址
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<AddressBook> showAddress(@PathVariable Long id){
        AddressBook addressBook = addressBookService.findAddressById(id);
        return R.success(addressBook);
    }


    /**
     * 修改地址
     * @param
     * @return
     */
    @PutMapping
    public R<String> updateAddress(@RequestBody AddressBook addressBook){
        addressBookService.updateAddress(addressBook);
        return R.success("");
    }

    /**
     * 设置默认地址
     * @param addressBook
     * @return
     */
    @PutMapping("default")
    public R<String> setAddressDefault(@RequestBody AddressBook addressBook,HttpSession session){
        Long userId = (Long) session.getAttribute("user");
        addressBook.setUserId(userId);
        addressBookService.setDefaultAddress(addressBook);
        return R.success("");
    }


    /**
     * 删除地址
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> deleteAddressBook(Long ids){
        addressBookService.deleteAddressBook(ids);
        return R.success("");
    }

    /**
     * 查询默认地址
     */
    @GetMapping("default")
    public R<AddressBook> getDefault(HttpSession session) {
        Long userId = (Long) session.getAttribute("user");
        AddressBook addressBook = addressBookService.getDefaultAddress(userId);

        if (null == addressBook) {
            return R.error("没有找到该对象");
        } else {
            return R.success(addressBook);
        }
    }
}
